package judy.freechart;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;



import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.TickUnitSource;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYDataset;


import org.apache.commons.lang.ArrayUtils;
/**
 * @author John B. Matthews
 */
public class JFreeChartDemo extends JFrame {
    
    private static final int MAX = 8;
    private static final Random random = new Random();
    private static DefaultXYDataset dataset = new DefaultXYDataset();
    private static JLabel addLabel;
    private static double series[][][];
    private static XYLineAndShapeRenderer renderer;
    private static String todayFileName;
    private static String fileName;
    /**
     * Construct a new frame 
     *
     * @param title the frame title
     */
    public JFreeChartDemo(String title) {
        super(title);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel labelPanel = new JPanel();
       
        addLabel = new JLabel("");        
        
        labelPanel.add(addLabel);
        this.add(labelPanel, BorderLayout.NORTH);
        
        
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("Shape Visible");
        buttonPanel.add(addButton);
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	if(renderer.getBaseShapesVisible())
            		renderer.setBaseShapesVisible(false);
            	
            	else
            		renderer.setBaseShapesVisible(true);
            }
        });
        JButton remButton = new JButton("Item Label Visible");
        buttonPanel.add(remButton);
        remButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	if(renderer.getBaseItemLabelsVisible())
            		renderer.setBaseItemLabelsVisible(false);
            	else
            		renderer.setBaseItemLabelsVisible(true);
            }
        });
        JButton refreshButton = new JButton("Refresh");
        buttonPanel.add(refreshButton);
        refreshButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	updateTodayData();
            }
        });
        this.add(buttonPanel, BorderLayout.SOUTH);
        
        
        getTodayFile();  
             
       
        
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart, false);
        chartPanel.setPreferredSize(new Dimension(640, 480));
        this.add(chartPanel, BorderLayout.CENTER);
 
       
        
        
        JMenu file = new JMenu("File");
        file.setMnemonic('F'); 
        JMenuItem openItem = new JMenuItem("Open");
        openItem.setMnemonic('O');
        file.add(openItem);
        openItem.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e)
					{
						FileFilter.open();
					}
				}
			);	
		JMenuItem exitItem = new JMenuItem("Exit");
		exitItem.setMnemonic('E');
		file.add(exitItem);	
		exitItem.addActionListener(
			new ActionListener(){
				public void actionPerformed(ActionEvent e)
				{
				//	System.out.println("Exit is pressed");
					System.exit(0);
				}
			}
		);						
		JMenuBar bar = new JMenuBar();
		setJMenuBar(bar);
		bar.add(file);
		
    }
    
    
    public static void trim(String name){
    	File f = new File(name);
    	if (f.exists()){
        	addLabel.setText(name);        
            ReadFile.setFileName(name);
            series= ReadFile.getSeries();
            for (int i=0; i<4; i++ ){	         	
            	
	            	for(int k=143;k>0;k--){
	            		
	            		if (series[i][0][k]==0 && series[i][1][k]==0 ){
	            			series[i][0]=ArrayUtils.remove(series[i][0],k);
	            			series[i][1]=ArrayUtils.remove(series[i][1],k);		            		
	            		}	            		
	            	}          	
	   
            }
         //   addLabel.setText(Integer.toString(dataset.getSeriesCount()));
            int count = dataset.getSeriesCount();
            for (int i=0;i<count;i++){            	
            	dataset.removeSeries("Machine-"+(i+1));
            }
           
        	for(int i=0;i<4;i++){
        		
        		dataset.addSeries("Machine-"+(i+1), series[i]);
        
        	}
           
          
        }
    }
    
    
  
    public static void getTodayFile(){

        Date today = new Date();  
        DateFormat df = new SimpleDateFormat("yyyy-M-d");
        String s = df.format(today);
        todayFileName = s+".ini";
        fileName = todayFileName;
        trim(fileName);
        //
    }
    public static void updateTodayData(){
    	if (fileName.equals(todayFileName)){
    		trim(fileName);
    		
    	}
    	else{
    		getTodayFile();
    		
    	}
    }
    
   
    /**
     * Create a chart.
     *
     * @param dataset the dataset
     * @return the chart
     */
    private JFreeChart createChart(XYDataset dataset) {

        // create the chart...
        JFreeChart chart = ChartFactory.createXYLineChart(
            "Machine Pressure Chart", // chart title
            "Time", // domain axis label
            "Pressure Value", // range axis label
            dataset,  // initial series
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
            );

        // set chart background
        chart.setBackgroundPaint(Color.white);

        // set a few custom plot features
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(new Color(0xffffe0));
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);

        // set the plot's axes to display integers
        TickUnitSource ticks = NumberAxis.createIntegerTickUnits();
        NumberAxis domain = (NumberAxis) plot.getDomainAxis();
        domain.setStandardTickUnits(ticks);
        NumberAxis range = (NumberAxis) plot.getRangeAxis();
        range.setStandardTickUnits(ticks);

        // render shapes and lines
        renderer =
            new XYLineAndShapeRenderer(true, true);
        plot.setRenderer(renderer);
        renderer.setBaseShapesVisible(false);
        renderer.setBaseShapesFilled(true);

        // set the renderer's stroke
        Stroke stroke = new BasicStroke(
            1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        renderer.setBaseOutlineStroke(stroke);

       
        
        // label the points
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        XYItemLabelGenerator generator =
            new StandardXYItemLabelGenerator(
                StandardXYItemLabelGenerator.DEFAULT_ITEM_LABEL_FORMAT,
                format, format);
        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(false);

        return chart;
    }
    
    public static class TaskThread extends Thread {
  	  public void run() {
  	    try {
  	      while(true) {
  	    	  updateTodayData();
  	    //	sleep(10 * 1000);
  	       sleep(10 * 60 * 1000);
  	      }
  	    } catch (Exception e) {
  	    }
  	  }
  	  
  	}
   
    /** Main method */
    public static void main(String[] args) {
    	
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFreeChartDemo demo = new JFreeChartDemo("JFreeChartDemo");
                demo.pack();
                demo.setLocationRelativeTo(null);
                demo.setVisible(true); 
                
              //update data every 10 mins
                TaskThread th = new TaskThread();
                th.start();
         //       System.out.print("hello1");
                
            }
         });
        
        
     
    }
    
    
   
}
